package com.lalameow.loginbylogingate.protocol;

import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.events.ListenerPriority;
import com.comphenix.protocol.events.PacketAdapter;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.events.PacketEvent;
import com.comphenix.protocol.wrappers.WrappedChatComponent;
import com.comphenix.protocol.wrappers.WrappedGameProfile;
import com.comphenix.protocol.wrappers.WrappedSignedProperty;
import com.google.gson.Gson;
import com.lalameow.loginbylogingate.LoginByLoginGate;
import com.lalameow.loginbylogingate.util.CryptUtil;
import com.lalameow.packet.pojo.AuthenticateClient;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.lang.reflect.InvocationTargetException;
import java.security.PublicKey;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * 创建人: 陈刚
 * 日期: 2018/5/15
 * 时间: 0:40
 * 功能：请进行修改
 */
public class LoginAuthPackHandler extends PacketAdapter {
    public LoginAuthPackHandler() {

        super(LoginByLoginGate.plugin, ListenerPriority.HIGHEST,  PacketType.Login.Client.ENCRYPTION_BEGIN);
    }


    @Override
    public void onPacketReceiving(PacketEvent event) {

        try {
            byte[] secretKeyEncrypted=(byte[]) event.getPacket().getModifier().read(0);
            byte[] verifyTokenEncrypted=(byte[]) event.getPacket().getModifier().read(1);
            SecretKey secretKey=new SecretKeySpec(CryptUtil.decryptData(LoginByLoginGate.privateKey,secretKeyEncrypted), "AES");
            byte[] decryptData=CryptUtil.decryptData(LoginByLoginGate.privateKey,verifyTokenEncrypted);
            decryptData=CryptUtil.decryptData(secretKey,decryptData);
            Gson gson=new Gson();
            AuthenticateClient authenticateClient=gson.fromJson(new String(decryptData),AuthenticateClient.class);
            LoginByLoginGate.plugin.getLoginGateClient().vaildClient(authenticateClient);
        } catch (NullPointerException | InterruptedException e){
            e.printStackTrace();
            diconnectPlayer(event.getPlayer(), ChatColor.RED+"登录异常，重新连接或者请联系管理员。。！");
        }catch (Exception e) {
            diconnectPlayer(event.getPlayer(), ChatColor.RED+"请使用本服务器专用客户端登录！");
        }finally {
            event.setCancelled(true);
        }
    }

    private void diconnectPlayer(Player player, String reson) {
        PacketContainer packetContainer=LoginByLoginGate.plugin.getProtocolManager().createPacket(PacketType.Login.Server.DISCONNECT);
        packetContainer.getChatComponents().write(0, WrappedChatComponent.fromText(reson));
        try {
            LoginByLoginGate.plugin.getProtocolManager().sendServerPacket(player,packetContainer);
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
